package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.assistant.common.vo.SessionInfo;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.*;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.common.enums.ArticleStatusEnum;
import com.bifang.module.system.common.enums.ContentTypeEnum;
import com.bifang.module.system.common.vo.appArticle.AppArticleAuthVO;
import com.bifang.module.system.common.vo.appArticle.AppArticleKeyVO;
import com.bifang.module.system.common.vo.appArticle.AppArticleStatusVO;
import com.bifang.module.system.common.vo.appArticle.AppArticleVO;
import com.bifang.module.system.core.dao.model.AppArticle;
import com.bifang.module.system.core.dao.service.AppArticleService;
import com.bifang.module.system.core.integration.AppArticleIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.EnrollStatusEnum;
import com.jwsoft.manager.common.enums.EnrollmenDictEnum;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduEnrollmenBrochure.*;
import com.jwsoft.manager.common.vo.eduFormSpecial.EduFormSpecialVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolKeyVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EnrollSubmitVO;
import com.jwsoft.manager.core.dao.model.EduEnrollmenBrochure;
import com.jwsoft.manager.core.dao.model.EduFormEnroll;
import com.jwsoft.manager.core.dao.model.EduSchool;
import com.jwsoft.manager.core.dao.model.EduSchoolConfig;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduEnrollmenBrochureIntegration;
import com.jwsoft.manager.core.integration.EduSchoolIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 各学校招生简章业务实现类
 *
 * @author chenchao
 * @since 2023-01-11
 */
@ApiService(funcCode = "Eduenrollmen", title = "各学校招生简章")
public class EduEnrollmenBrochureIntegrationImpl implements EduEnrollmenBrochureIntegration {

    @Autowired
    public EduEnrollmenBrochureService eduEnrollmenBrochureService;
    @Autowired
    private DictHelper dictHelper;

    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduSchoolIntegration eduSchoolIntegration;

    @Autowired
    private AppArticleService appArticleService;

    @Autowired
    private AppArticleIntegration appArticleIntegration;

    @Autowired
    private EduFormEnrollService eduFormEnrollService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private EduSchoolConfigService eduSchoolConfigService;

    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private EduStudentEnrollKindergartenService eduStudentEnrollKindergartenService;
    @Autowired
    private EduEnrollClearCacheHelper enrollClearCacheHelper;

    @Autowired
    public DictIntegration dictIntegration;

    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;

    @Override
    @OpApi(funcCode = "Eduenrollmen0001", title = "管理端招生方案管理各学校招生简章分页查询", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public PageInfo<EnrollmenBrochureVO> getList(EnrollmenQueryVO vo) {
        Map<String, Object> queryMap = BeanUtil.beanToMap(vo, false, true);
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取30条
            vo.setPageNum(1);
            vo.setPageSize(30);
        }
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        } else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (!CollectionUtils.isEmpty(areaCodeList)) {
            queryMap.put("areaCodeList", areaCodeList);
        } else {
            throw new AppException("必须传入行政区划");
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EnrollmenBrochureVO> appNotices = eduEnrollmenBrochureService.getManEnrollMenInfoList(queryMap);
        if (CollectionUtils.isEmpty(appNotices)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        PageInfo<EnrollmenBrochureVO> pageInfo = new PageInfo<>(appNotices);
        Long currentTime = System.currentTimeMillis();
        dictHelper.valueToName(pageInfo.getList(), Arrays.asList(EnrollmenDictEnum.values()));
        pageInfo.getList().forEach(
                item -> {
                    setPublishTime(item, currentTime);
                });

        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0002", title = "家长端各学校招生简章根据主键查询详情", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public EnrollmenBrochureVO getById(EduEnrollmenBrochureKeyVO vo) {
        EnrollmenBrochureVO brochureVO = eduEnrollmenBrochureService.getDetail(vo);
        //获取学校信息
        if (StringUtils.isNotBlank(brochureVO.getSchoolId())) {
            EduSchoolKeyVO keyVO = new EduSchoolKeyVO();
            keyVO.setOrgId(brochureVO.getSchoolId());
            keyVO.setAccessToken(vo.getAccessToken());
            EduSchoolVO eduSchool = eduSchoolIntegration.getById(keyVO);
            if (eduSchool != null) {
                brochureVO.setSchoolName(eduSchool.getSchoolName());
                brochureVO.setLatitude(eduSchool.getLatitude());
                brochureVO.setLongitude(eduSchool.getLongitude());
                brochureVO.setShortName(eduSchool.getShortName());
                brochureVO.setSchoolNature(eduSchool.getSchoolNature());
                brochureVO.setEnrollStatus(eduSchool.getEnrollStatus());
                brochureVO.setSchoolCategory(eduSchool.getSchoolCategory());
            } else {
                throw new AppException("学校信息不存在");
            }
        }
        Integer year = eduHelper.thisYear();
        if (year > brochureVO.getYear()) {
            brochureVO.setEnrollStatus(EnrollStatusEnum.finish.getType());
            brochureVO.setEnrollMessage(brochureVO.getYear() + "年度招生工作已结束！");
        } else if (year - brochureVO.getYear() == 0) {
            if (EnrollStatusEnum.wait.getType().equalsIgnoreCase(brochureVO.getEnrollStatus())) {
                brochureVO.setEnrollMessage(brochureVO.getYear() + "年度招生工作尚未开始！");
            } else if (EnrollStatusEnum.finish.getType().equalsIgnoreCase(brochureVO.getEnrollStatus())) {
                brochureVO.setEnrollMessage(brochureVO.getYear() + "年度招生工作已结束！");
            } else if (EnrollStatusEnum.on.getType().equalsIgnoreCase(brochureVO.getEnrollStatus())) {
                brochureVO.setEnrollMessage(brochureVO.getYear() + "招生中");
            }
        } else {
            brochureVO.setEnrollStatus(EnrollStatusEnum.wait.getType());
            brochureVO.setEnrollMessage(brochureVO.getYear() + "年度招生工作尚未开始！");
        }
        Long currentTime = System.currentTimeMillis();
        setPublishTime(brochureVO, currentTime);
        return brochureVO;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0020", title = "管理端各学校招生简章根据主键查询详情", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public EnrollmenBrochureVO getByIdPc(EduEnrollmenBrochureQueryVO vo) {
        EduEnrollmenBrochureKeyVO keyVO = Convert.convert(EduEnrollmenBrochureKeyVO.class, vo);
        if (StringUtils.isNotBlank(vo.getEnrollmenBrochureId()) || vo.getArticleId() != null) {
            return getById(keyVO);
        } else {
            if (StringUtils.isBlank(vo.getSchoolId())) {
                vo.setSchoolId(SessionUtil.getOrgId());
            }
            if (StringUtils.isBlank(vo.getSchoolId())) {
                throw new AppException("学校id不能为空");
            }
            Integer year = eduHelper.thisYear();
            QueryWrapper<EduEnrollmenBrochure> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduEnrollmenBrochure::getSchoolId, vo.getSchoolId())
                    .eq(EduEnrollmenBrochure::getYear, year);
            EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(queryWrapper, false);
            if (eduEnrollmenBrochure != null) {
                keyVO.setEnrollmenBrochureId(eduEnrollmenBrochure.getEnrollmenBrochureId());
                return getById(keyVO);
            } else {
                EnrollmenBrochureVO enrollmenBrochureVO = new EnrollmenBrochureVO();
                EduSchoolVO school = eduSchoolService.getDetail(vo.getSchoolId());
                if (school == null) {
                    throw new AppException("学校基础信息不存在，不能新增招生方案，请联系系统管理员");
                }
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(school.getRecruitStatus())) {
                    throw new AppException("学校已停止招生，不能新增招生方案");
                }

                enrollmenBrochureVO.setLongitude(school.getLongitude());
                enrollmenBrochureVO.setLatitude(school.getLatitude());
                enrollmenBrochureVO.setSchoolName(school.getSchoolName());
                enrollmenBrochureVO.setShortName(school.getShortName());
                enrollmenBrochureVO.setSchoolNature(school.getSchoolNature());
                enrollmenBrochureVO.setYear(year);
                enrollmenBrochureVO.setContentType(ContentTypeEnum.richText.getType());
                enrollmenBrochureVO.setSchoolId(vo.getSchoolId());
                enrollmenBrochureVO.setSchoolCategory(school.getSchoolCategory());
                enrollmenBrochureVO.setAreaCode(school.getAreaCode());
                return enrollmenBrochureVO;
            }
        }

    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "Eduenrollmen0003", title = "各学校招生简章保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduEnrollmenBrochureVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
        if (!CollectionUtils.isEmpty(vo.getEnrollAreaConfigList())){
            vo.setAdmissionsCategory(JSON.toJSONString(vo.getEnrollAreaConfigList()));
        }else{
            vo.setAdmissionsCategory("");
        }
        if (!CollectionUtils.isEmpty(vo.getEnrollAreaList())){
            vo.setEnrollArea(JSON.toJSONString(vo.getEnrollAreaList()));
        }else{
            vo.setEnrollArea("");
        }
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0004", title = "各学校招生简章新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "Eduenrollmen0004",
            operationName = "各学校招生简章新增",
            dataType = "enrollmenBrochureId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduEnrollmenBrochureVO add(EduEnrollmenBrochureVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduEnrollmenBrochure entity = Convert.convert(EduEnrollmenBrochure.class, vo);
        eduEnrollmenBrochureService.save(entity);
        clearCacheAreaCode(entity.getAreaCode());
        //将主键设置回vo使操作日志可以取到
        vo.setEnrollmenBrochureId(entity.getEnrollmenBrochureId());
        eduSchoolService.clearCache(entity.getSchoolId(), entity.getAreaCode());
        return vo;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0005", title = "各学校招生简章修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0005",
            operationName = "各学校招生简章修改",
            dataType = "enrollmenBrochureId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduEnrollmenBrochureVO edit(EduEnrollmenBrochureVO vo) {
        if (ObjectUtils.isEmpty(vo.getEnrollmenBrochureId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduEnrollmenBrochure oldEntity = eduEnrollmenBrochureService.getById(vo.getEnrollmenBrochureId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduEnrollmenBrochure entity = Convert.convert(EduEnrollmenBrochure.class, vo);
        eduEnrollmenBrochureService.updateById(entity);
        clearCache(entity.getEnrollmenBrochureId());
        clearCacheAreaCode(entity.getAreaCode());
        eduSchoolService.clearCache(entity.getSchoolId(), entity.getAreaCode());
        return vo;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0006", title = "各学校招生简章根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "Eduenrollmen0006",
            operationName = "各学校招生简章删除",
            dataType = "enrollmenBrochureId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduEnrollmenBrochureKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getEnrollmenBrochureId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduEnrollmenBrochure entity = eduEnrollmenBrochureService.getById(vo.getEnrollmenBrochureId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduEnrollmenBrochureService.removeById(vo.getEnrollmenBrochureId());
        clearCache(vo.getEnrollmenBrochureId());
        clearCacheAreaCode(entity.getAreaCode());
        eduSchoolService.clearCache(entity.getSchoolId(), entity.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0007", title = "家长端招生方案信息列表", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public PageInfo<EnrollmenBrochureVO> getEnrollmenList(EnrollmenQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(100);
        }
        if(StringUtils.isBlank(vo.getArticleStatus())) {
            vo.setArticleStatus(ArticleStatusEnum.on.getType());
        }

        Map<String, Object> queryMap = BeanUtil.beanToMap(vo, false, true);
        SessionInfo sessionInfo = SessionUtil.getSessionInfo();
        if (sessionInfo != null) {
            if (!CollectionUtils.isEmpty(sessionInfo.getLabelList())) {
                queryMap.put("labelList", sessionInfo.getLabelList());
            }
        }

        if (StringUtils.isNotBlank(vo.getSearchText())) {
            List<String> searchTextList = new ArrayList<>();
            searchTextList.add(vo.getSearchText());
            queryMap.put("searchTextList", searchTextList);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EnrollmenBrochureVO> resultList = eduEnrollmenBrochureService.getEnrollMenInfoList(queryMap);
        if (CollectionUtils.isEmpty(resultList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        PageInfo<EnrollmenBrochureVO> pageInfo = new PageInfo<>(resultList);
        Long currentTime = System.currentTimeMillis();
        dictHelper.valueToName(resultList, Arrays.asList(EnrollmenDictEnum.values()));
        resultList.forEach(
                item -> {
                    setPublishTime(item, currentTime);
                });

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }


    @Override
    @OpApi(funcCode = "Eduenrollmen0009", title = "招生方案草稿转审核中", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0009",
            operationName = "招生方案草稿转审核中",
            dataType = "enrollmenBrochureId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void submitEnroll(EnrollSubmitVO vo) {
        String enrollmenBrochureId = vo.getEnrollmenBrochureId();
        EduEnrollmenBrochure enrollmenBrochure =
                eduEnrollmenBrochureService.getById(enrollmenBrochureId);
        Assert.notNull(enrollmenBrochure, "查询不到招生信息");
        AppArticle appArticle = appArticleService.getById(enrollmenBrochure.getArticleId());
        if (appArticle == null) {
            throw new AppException("未找到招生方案内容信息信息");
        }
        if (!ArticleStatusEnum.draft.getType().equals(appArticle.getArticleStatus())) {
            throw new AppException("不是草稿状态，不能提交审核");
        }
        appArticle.setArticleStatus(ArticleStatusEnum.auth.getType());
        appArticle.setAuthStatus(AuthStatusEnum.NODO.getType());
        appArticleService.updateById(appArticle);
        QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
        formQueryWrapper
                .lambda()
                .eq(EduFormEnroll::getFormRefId, enrollmenBrochureId)
                .eq(EduFormEnroll::getValidStatus, BoolEnum.TRUE.getType())
                .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure");
        List<EduFormEnroll> formList = eduFormEnrollService.list(formQueryWrapper);
        if (formList.size() > 0) {
            formList.forEach(
                    item -> {
                        item.setStatus(ArticleStatusEnum.auth.getType());
                        item.setValidStatus(BoolEnum.TRUE.getType());
                    });
            eduFormEnrollService.updateBatchById(formList);
        } else {
            if (SchoolCategoryEnum.KINDERGARTEN.getType().equals(enrollmenBrochure.getSchoolCategory())) {
                throw new AppException("表单未配置，不能提交审核");
            }
        }
        clearCache(enrollmenBrochure.getEnrollmenBrochureId());
        clearCacheAreaCode(enrollmenBrochure.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0016", title = "招生方案上下架", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0016",
            operationName = "招生方案上下架",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void editPublish(AppArticleStatusVO vo) {
        Long id = vo.getArticleId();
        Assert.notNull(id, "查询失败，招生方案信息主键为空！");
        QueryWrapper<EduEnrollmenBrochure> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduEnrollmenBrochure::getArticleId, id);
        EduEnrollmenBrochure brochure = eduEnrollmenBrochureService.getOne(queryWrapper);
        if (brochure == null) {
            throw new AppException("未找到招生方案信息");
        }
        appArticleIntegration.editPublish(vo);
        UpdateWrapper<EduFormEnroll> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(EduFormEnroll::getFormRefId, brochure.getEnrollmenBrochureId())
                .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure")
                .set(EduFormEnroll::getStatus, vo.getArticleStatus());
        eduFormEnrollService.update(updateWrapper);
        clearCache(brochure.getEnrollmenBrochureId());
        clearCacheAreaCode(brochure.getAreaCode());
        QueryWrapper<EduFormEnroll> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().eq(EduFormEnroll::getFormRefId, brochure.getEnrollmenBrochureId())
                .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure");
        List<EduFormEnroll> eduFormEnrollList = eduFormEnrollService.list(enrollQueryWrapper);
        if (!CollectionUtils.isEmpty(eduFormEnrollList)) {
            for (EduFormEnroll eduFormEnroll : eduFormEnrollList) {
                enrollClearCacheHelper.clearCacheEnrollFormParams(eduFormEnroll.getFormId());
            }

        }
        eduSchoolService.clearCache(brochure.getSchoolId(), brochure.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0017", title = "招生方案审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0017",
            operationName = "招生方案审核",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void auth(EnrollmenAuthVO vo) {
        Long id = vo.getArticleId();
        Assert.notNull(id, "查询失败，招生方案信息主键为空！");

        Integer year = eduHelper.thisYear();
//        幼儿园是同时的义务段是分开的
        if ("1".equals(vo.getClassify())) {
            UpdateWrapper<EduSchoolConfig> configUpdateWrapper = new UpdateWrapper<>();
            configUpdateWrapper.lambda().eq(EduSchoolConfig::getSchoolId, vo.getSchoolId())
                    .eq(EduSchoolConfig::getYear, year)
                    .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                    .set(EduSchoolConfig::getAuthStatus, vo.getAuthStatus());
            eduSchoolConfigService.update(configUpdateWrapper);
        }

        QueryWrapper<EduEnrollmenBrochure> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduEnrollmenBrochure::getArticleId, id);
        EduEnrollmenBrochure brochure = eduEnrollmenBrochureService.getOne(queryWrapper);
        if (brochure == null) {
            throw new AppException("未找到招生方案信息");
        }
        AppArticleAuthVO articleAuthVO = Convert.convert(AppArticleAuthVO.class, vo);
        appArticleIntegration.auth(articleAuthVO);
        LambdaQueryWrapper<AppArticle> query = new QueryWrapper<AppArticle>().lambda().select(AppArticle::getAuthStatus).eq(AppArticle::getArticleId, articleAuthVO.getArticleId());
        AppArticle article = appArticleService.getOne(query);
        //审核通过更新eduschool
        if (article.getAuthStatus().equals(BoolEnum.TRUE.getType())) {
            EduSchool eduSchool=eduSchoolService.getById(brochure.getSchoolId());
            if(eduSchool!=null){
                eduSchool.setHouseEndTimeNo(brochure.getHouseEndTimeNo());
                eduSchool.setHouseEndTime(brochure.getHouseEndTime());
                eduSchool.setHouseEndTimeFw(brochure.getHouseEndTimeFw());
                eduSchool.setAuthOrderByNo(brochure.getAuthOrderByNo());
                eduSchool.setHouseholdEndTimeNo(brochure.getHouseholdEndTimeNo());
                eduSchool.setHouseholdEndTime(brochure.getHouseholdEndTime());
                eduSchool.setHouseholdEndTimeFw(brochure.getHouseholdEndTimeFw());
                eduSchool.setServiceFlag(brochure.getServiceFlag());
                eduSchoolService.updateById(eduSchool);
            }
        }
        clearCache(brochure.getEnrollmenBrochureId());
        clearCacheAreaCode(brochure.getAreaCode());
    }


    @Override
    @OpApi(funcCode = "Eduenrollmen0011", title = "新增或更新招生方案", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "Eduenrollmen0011",
            operationName = "新增或更新招生方案",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public String saveEnroll(EnrollmenVO vo) {

        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }
        String orgId = SessionUtil.getSessionInfo().getOrgId();
        if (StringUtils.isBlank(vo.getSchoolId())) {
            vo.setSchoolId(orgId);
            vo.setOrgId(orgId);
        } else {
            vo.setOrgId(vo.getSchoolId());
        }

        EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
        if (eduSchoolVO == null) {
            throw new AppException("学校信息不存在！");
        }
        if (StringUtils.isBlank(vo.getEnrollmenBrochureId())) {
            QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
            brochureQueryWrapper.lambda().select(EduEnrollmenBrochure::getEnrollmenBrochureId, EduEnrollmenBrochure::getArticleId).eq(EduEnrollmenBrochure::getYear, vo.getYear())
                    .eq(EduEnrollmenBrochure::getSchoolId, vo.getSchoolId());
            List<EduEnrollmenBrochure> brochureList = eduEnrollmenBrochureService.list(brochureQueryWrapper);
            if (!CollectionUtils.isEmpty(brochureList)) {
                EduEnrollmenBrochure brochure=brochureList.get(0);
                vo.setEnrollmenBrochureId(brochure.getEnrollmenBrochureId());
                vo.setArticleId(brochure.getArticleId());
            }
        }
        Set<String> systemPrivileges = SessionUtil.getSystemPrivileges();
        boolean supAdmin = false;
        if (!CollectionUtils.isEmpty(systemPrivileges) && systemPrivileges.contains(SysPermissionEnum.superadmin.getType())) {
            supAdmin = true;
        }else {
            EduSchoolVO userSchool = eduSchoolService.getDetail(orgId);
            if (userSchool == null) {
                supAdmin = true;
            }
        }
        AppArticleVO articleVO = Convert.convert(AppArticleVO.class, vo);

        Long articleId;
        if (ObjectUtils.isEmpty(vo.getArticleId())) {
            if (StringUtils.isBlank(articleVO.getShowPosition())) {
                articleVO.setShowPosition("20");
            }
            if (StringUtils.isBlank(articleVO.getShowType())) {
                articleVO.setShowType("0");
            }
            articleVO.setPublisher(eduSchoolVO.getSchoolName());
            articleVO.setAuthStatus(AuthStatusEnum.NODO.getType());
            articleVO.setAuthTime(null);
            articleVO.setAuthRemarks(null);
            articleId = appArticleIntegration.add(articleVO).getArticleId();
        } else {
            if (supAdmin) {
                articleId = appArticleIntegration.editAdmin(articleVO).getArticleId();
            } else {
                articleId = appArticleIntegration.edit(articleVO).getArticleId();
            }
        }

        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        if (StringUtils.isBlank(vo.getAreaCode())) {
            throw new AppException("行政区划不能为空！");
        }

        EduEnrollmenBrochure eduEnrollmenBrochure = Convert.convert(EduEnrollmenBrochure.class, vo);
        eduEnrollmenBrochure.setArticleId(articleId);
        eduEnrollmenBrochure.setSchoolId(vo.getOrgId());
        if (ObjectUtils.isEmpty(eduEnrollmenBrochure.getEnrollmenBrochureId())) {
            eduEnrollmenBrochure.setEnrollmenBrochureId(IdUtil.simpleUUID());
        } else {
            if (!supAdmin) {
                QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
                formQueryWrapper
                        .lambda()
                        .eq(EduFormEnroll::getFormRefId, eduEnrollmenBrochure.getEnrollmenBrochureId())
                        .eq(EduFormEnroll::getValidStatus, BoolEnum.TRUE.getType())
                        .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure");
                List<EduFormEnroll> formList = eduFormEnrollService.list(formQueryWrapper);
                if (formList.size() > 0) {
                    formList.forEach(
                            item -> {
                                item.setStatus(ArticleStatusEnum.draft.getType());
                                item.setValidStatus(BoolEnum.TRUE.getType());
                            });
                    eduFormEnrollService.updateBatchById(formList);
                }
            }
        }
        eduEnrollmenBrochure.setSchoolId(vo.getOrgId());
        if (ObjectUtils.isEmpty(eduEnrollmenBrochure.getEndRegistration())) {
            eduEnrollmenBrochure.setEndRegistration(BoolEnum.FALSE.getType());
        }
        int lastYear = vo.getYear() - 1;
        QueryWrapper<EduEnrollmenBrochure> oldBrochureQueryWrapper = new QueryWrapper<>();
        oldBrochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getSchoolId, vo.getOrgId())
                .eq(EduEnrollmenBrochure::getYear, lastYear);
        EduEnrollmenBrochure oldBrochure = eduEnrollmenBrochureService.getOne(oldBrochureQueryWrapper, false);
        if (oldBrochure != null) {
            if (!StringUtils.isBlank(oldBrochure.getMapRegion())) {
                eduEnrollmenBrochure.setMapRegion(oldBrochure.getMapRegion());
            }
        }
        if (!CollectionUtils.isEmpty(vo.getEnrollAreaConfigList())){
            eduEnrollmenBrochure.setAdmissionsCategory(JSON.toJSONString(vo.getEnrollAreaConfigList()));
        }else{
            eduEnrollmenBrochure.setAdmissionsCategory("");
        }
        eduEnrollmenBrochureService.saveOrUpdate(eduEnrollmenBrochure);
        clearCache(eduEnrollmenBrochure.getEnrollmenBrochureId());
        clearCacheAreaCode(eduEnrollmenBrochure.getAreaCode());
        eduSchoolService.clearCache(eduEnrollmenBrochure.getSchoolId(),eduEnrollmenBrochure.getAreaCode());
        return eduEnrollmenBrochure.getEnrollmenBrochureId();
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0012", title = "驳回招生方案", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "Eduenrollmen0012",
            operationName = "驳回招生方案",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void rejectEnroll(EnrollmenVO vo) {
        AppArticleKeyVO queryVO = new AppArticleKeyVO();
        queryVO.setArticleId(vo.getArticleId());
        AppArticleVO articleVO = appArticleIntegration.getById(queryVO);
        articleVO.setAuthStatus(AuthStatusEnum.NODO.getType());
        articleVO.setAuthTime(null);
        articleVO.setAuthRemarks(null);
        articleVO.setAccessToken(vo.getAccessToken());
        articleVO.setOpRouterId(vo.getOpRouterId());
        appArticleIntegration.back(queryVO);
        EduEnrollmenBrochure eduEnrollmenBrochure = Convert.convert(EduEnrollmenBrochure.class, vo);
        eduEnrollmenBrochure.setArticleId(queryVO.getArticleId());
        eduEnrollmenBrochure.setSchoolId(vo.getOrgId());
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getArticleId, vo.getArticleId());
        EduEnrollmenBrochure brochure = eduEnrollmenBrochureService.getOne(brochureQueryWrapper, false);
        if (ObjectUtils.isEmpty(brochure.getEnrollmenBrochureId())) {
            throw new AppException("查询不到招生方案信息");
        } else {
            QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
            formQueryWrapper
                    .lambda()
                    .eq(EduFormEnroll::getFormRefId, brochure.getEnrollmenBrochureId())
                    .eq(EduFormEnroll::getFormRefName, "edu_enrollmen_brochure");
            List<EduFormEnroll> formList = eduFormEnrollService.list(formQueryWrapper);
            if (formList.size() > 0) {
                formList.forEach(
                        item -> {
                            item.setStatus(ArticleStatusEnum.draft.getType());
                        });
                eduFormEnrollService.updateBatchById(formList);
            }
        }
        clearCache(eduEnrollmenBrochure.getEnrollmenBrochureId());
        clearCacheAreaCode(eduEnrollmenBrochure.getAreaCode());
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0013", title = "义务教育关联特殊通道表单", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "Eduenrollmen0013",
            operationName = "义务教育关联特殊通道表单",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void saveYwSpecialFormInfo(EduFormSpecialVO vo) {
        String brochureId = vo.getEnrollmenBrochureId();
        Assert.hasText(brochureId, "招生方案id不能为空");
        EduEnrollmenBrochure brochure = eduEnrollmenBrochureService.getById(brochureId);
        String formSpecialId = vo.getFormSpecialId();
        if (!ObjectUtils.isEmpty(brochure.getSpecialIds())) {
            String[] specialIds = StringUtils.split(brochure.getSpecialIds(), ",");
            List<String> specialIdtList = new ArrayList<>(specialIds.length);
            Collections.addAll(specialIdtList, specialIds);
            if (vo.getChecked()) {
                specialIdtList.add(formSpecialId);
                brochure.setSpecialIds(String.join(",", specialIdtList));
            } else {
                brochure.setSpecialIds(
                        specialIdtList.stream()
                                .filter(item -> !StringUtils.equals(item, formSpecialId))
                                .collect(Collectors.joining(",")));
            }
        } else {
            if (vo.getChecked()) {
                brochure.setSpecialIds(formSpecialId);
            }
        }
        eduEnrollmenBrochureService.updateById(brochure);
    }


    @Override
    @OpApi(funcCode = "Eduenrollmen0015", title = "一键上架", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "Eduenrollmen0015",
            operationName = "一键上架",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchPublish(EnrollmenVO vo) {
        EnrollmenQueryVO enrollmenQueryVO = Convert.convert(EnrollmenQueryVO.class, vo);
        enrollmenQueryVO.setArticleStatus("finish");
        enrollmenQueryVO.setYear(eduHelper.thisYear());
        PageInfo<EnrollmenBrochureVO> brochureVOPageInfo = getEnrollmenList(enrollmenQueryVO);
        if (!CollectionUtils.isEmpty(brochureVOPageInfo.getList())) {
            for (int i = 0; i < brochureVOPageInfo.getList().size(); i++) {
                EnrollmenBrochureVO enrollmenBrochureVO = brochureVOPageInfo.getList().get(i);
                AppArticleStatusVO statusVO = Convert.convert(AppArticleStatusVO.class, enrollmenBrochureVO);
                statusVO.setArticleStatus("on");
                this.editPublish(statusVO);
            }

        }
    }


    //清除缓存
    private void clearCache(String enrollmenBrochureId) {
        if (StringUtils.isNotBlank(enrollmenBrochureId)) {
            Cache cache = JetCacheUtils.create(EduCache.EDU_BROCHURE_ID, CacheType.BOTH);
            if (cache != null) {
                cache.remove(enrollmenBrochureId);
            }
        }
    }

    private void clearCacheAreaCode(String areaCode) {
        if (StringUtils.isNotBlank(areaCode)) {
            Cache cache = JetCacheUtils.create(EduCache.EDU_BROCHURE_areaCode, CacheType.BOTH);
            if (cache != null) {
                cache.remove(areaCode);
            }
        }
    }

    private void setPublishTime(EnrollmenBrochureVO enrollmenVO, Long currentTime) {
        int currentYear = DateUtil.date(currentTime).year();

        if (enrollmenVO.getPublishTime() != null) {
            int publishYear = DateUtil.year(enrollmenVO.getPublishTime());
            Long pulishTime = enrollmenVO.getPublishTime().getTime();
            Long time = (currentTime - pulishTime) / 1000;
            if (time < 600) {
                enrollmenVO.setPublishTimeText("刚刚");
            } else if (time >= 600 && time < 3600) {
                enrollmenVO.setPublishTimeText(time / 60 + "分钟前");
            } else if (time >= 3600 && time < 86400) {
                enrollmenVO.setPublishTimeText(time / 3600 + "小时前");
            } else if (time >= 86400 && time <= 864000) {
                enrollmenVO.setPublishTimeText(time / 86400 + "天前");
            } else if (time > 864000 && currentYear == publishYear) {
                enrollmenVO.setPublishTimeText(
                        DateUtil.format(enrollmenVO.getPublishTime(), "MM-dd HH:mm"));
            } else {
                enrollmenVO.setPublishTimeText(
                        DateUtil.format(enrollmenVO.getPublishTime(), "yyyy-MM-dd"));
            }
            if (StringUtils.isBlank(enrollmenVO.getShowType())) {
                enrollmenVO.setShowType("0");
            }
        } else {
            enrollmenVO.setPublishTimeText("时间丢失");
        }
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0018", title = "招生区域根据schoolId和year查询", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public List<EnrollmenBrochureVO> getEnrollmenBrochure(enrollmenBrochureSearchVO vo) {
        String schoolId = SessionUtil.getOrgId();
        if (StringUtils.isEmpty(schoolId)) {
            throw new AppException("schoolId不能为空");
        }
        QueryWrapper<EduEnrollmenBrochure> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(EduEnrollmenBrochure::getEnrollmenBrochureId, EduEnrollmenBrochure::getMapRegion)
                .eq(EduEnrollmenBrochure::getSchoolId,
                        schoolId)
                .eq(!ObjectUtils.isEmpty(vo.getYear()),
                        EduEnrollmenBrochure::getYear,
                        vo.getYear());
        List<EduEnrollmenBrochure> list = eduEnrollmenBrochureService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return null;
        }
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EnrollmenBrochureVO> resultList = Convert.toList(EnrollmenBrochureVO.class, list);
        return resultList;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0019", title = "招生区域修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0019",
            operationName = "招生区域修改",
            dataType = "enrollmenBrochureId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void editCoordinate(enrollmenBrochureUpdateVO vo) {
        if (ObjectUtils.isEmpty(vo.getEnrollmenBrochureId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduEnrollmenBrochure entity = eduEnrollmenBrochureService.getById(vo.getEnrollmenBrochureId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存数据
        entity.setMapRegion(vo.getMapRegion());
        eduEnrollmenBrochureService.updateById(entity);
        clearCache(entity.getEnrollmenBrochureId());
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0021", title = "查询招生方案的户籍、房产截止时间", funcType = FuncTypeEnum.query, publicFlag = BoolEnum.TRUE, savelog = false)
    public EduEnrollmenBrochureVO queryHjFcEndTime(EduEnrollmenBrochureQueryVO vo) {
        //获取招生配置参数
        EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
        queryVO.setAreaCode(vo.getAreaCode());
        queryVO.setYear(vo.getYear());
        queryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryVO);
        if (eduOperationCacheVO == null) {
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }
        Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
        EduEnrollmenBrochureVO brochureVO = new EduEnrollmenBrochureVO();
        EduOperationCacheDetailVO fcOperation = operation.get("YW024");
        brochureVO.setHouseEndTime(fcOperation.getEndTime());
        EduOperationCacheDetailVO yw060Operation = operation.get("YW060");
        brochureVO.setHouseEndTimeFw(yw060Operation.getEndTime());
        EduOperationCacheDetailVO yw025Operation = operation.get("YW025");
        brochureVO.setHouseholdEndTime(yw025Operation.getEndTime());
        EduOperationCacheDetailVO yw061Operation = operation.get("YW061");
        brochureVO.setHouseholdEndTimeFw(yw061Operation.getEndTime());
        return brochureVO;
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0022", title = "招生方案批量审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0022",
            operationName = "招生方案批量审核",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchAuth(BatchEnrollmentVO vo) {
        if (CollectionUtils.isEmpty(vo.getArticleIds())){
            throw new AppException("请选择审核的招生方案");
        }
        if(StringUtils.isBlank(vo.getAuthStatus())){
            throw new AppException("请选择审核状态");
        }
        List<Long> articleIds = vo.getArticleIds();
        for (Long articleId : articleIds) {
            EnrollmenAuthVO authVO = new EnrollmenAuthVO();
            authVO.setArticleId(articleId);
            authVO.setAuthStatus(vo.getAuthStatus());
            authVO.setClassify(vo.getClassify());
            this.auth(authVO);
        }
    }

    @Override
    @OpApi(funcCode = "Eduenrollmen0023", title = "批量招生方案上下架", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "Eduenrollmen0023",
            operationName = "批量招生方案上下架",
            dataType = "articleId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchEditPublish(BatchEnrollmentVO vo) {
        if (CollectionUtils.isEmpty(vo.getArticleIds())){
            throw new AppException("请选择批量修改的招生方案");
        }
        if(StringUtils.isBlank(vo.getArticleStatus())){
            throw new AppException("文章上/下状态不能为空");
        }
        List<Long> articleIds = vo.getArticleIds();
        for (Long articleId : articleIds) {
            AppArticleStatusVO authVO = new AppArticleStatusVO();
            authVO.setArticleId(articleId);
            authVO.setArticleStatus(vo.getArticleStatus());
            this.editPublish(authVO);
        }
    }
}
